from django.http import *
from google.appengine.api.labs import taskqueue
from google.appengine.ext.db import Key
from db import build_query

def simple_batch(request, cls, filters, url, callback, num_per_request=5, countdown=0):
    filters.append(lambda q: q.order('__key__'))

    if request.REQUEST.has_key('key'):
        key = Key(request.REQUEST['key'])
        filters.append(lambda q: q.filter('__key__ >=', key))
        
    objs = build_query(cls, filters).fetch(num_per_request+1)
    
    has_next = False
    if len(objs) > num_per_request:
         has_next = True    
    
    callback(objs[:num_per_request], has_next)

    if has_next:
        # Add the task to the default queue.
        key_str = str(objs[num_per_request].key())
        if len(key_str) < 500:
            taskqueue.add(url=url, countdown=countdown, params={'key': key_str}, name=key_str)
        else:
            taskqueue.add(url=url, countdown=countdown, params={'key': key_str})

    return HttpResponse('Done!')
